import React, { Component, Fragment } from 'react';
import { Modal, Form, message, Upload, Button, Icon, Input, Select } from 'antd';
import { citys, cityArea } from '../../utils/city';
import styles from '../../routes/Program/MatterDetail.less';

const FormItem = Form.Item;
const Option = Select.Option;
const cityArray = Object.keys(citys);
export default class UpLoadForm extends Component {
  state = {
    fileList: [],
    uploading: false,
    type: 'media',
    isChangeType: false,
    city: cityArray[0],
    area: cityArea[cityArray[0]],
    filetypenew: 'jpg',
    fileurl: 'F:\\test.mp4',
    thumnaildata: '',
  };
  componentDidMount() {}

  getObjectURL = file => {
    let url = null;
    if (window.createObjectURL !== undefined) {
      // basic
      url = window.createObjectURL(file);
    } else if (window.URL !== undefined) {
      // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) {
      // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  };

  vload = () => {
    //console.log('vload------------>');

    let obj = document.getElementById('video');
    //  obj.removeAttr("poster");
    //  const vimg = ("<img/>")[0];
    let thumnail = document.getElementById('thumnail');
    this.captureImage(obj, thumnail);
    //   obj.after(vimg);
    //   obj.remove();
  };

  captureImage = (video, thumnail) => {
    // 截图
    try {
      const scale = 0.3; // 缩放
      let videocanvas = document.getElementById('thumnail_canvas');
      videocanvas.width = video.videoWidth * scale;
      videocanvas.height = video.videoHeight * scale;
      videocanvas.getContext('2d').drawImage(video, 0, 0, videocanvas.width, videocanvas.height);
      document.getElementById('thumnail').setAttribute('crossOrigin', 'anonymous');
      document.getElementById('thumnail').src = videocanvas.toDataURL('image/jpeg');
      //console.log('toDataURL------------>', videocanvas.toDataURL('image/jpeg'));
      this.setState({ thumnaildata: videocanvas.toDataURL('image/jpeg') });
      // delete videocanvas;
    } catch (e) {
      //  output.src = "加载动画.gif";
    }
  };

  setImage = (src, w, h) => {
    this.resizeImage(
      src,
      data => {
        document.getElementById('thumnail').src = data;
        this.setState({ thumnaildata: data });
      },
      w,
      h
    );
  };
  resizeImage = (src, callback, w, h) => {
    let canvas = document.getElementById('thumnail_canvas');
    let ctx = canvas.getContext('2d');
    let im = new Image();
    w = w || 0;
    h = h || 0;
    im.onload = function() {
      // 为传入缩放尺寸用原尺寸
      !w && (w = this.width);
      !h && (h = this.height);
      //以长宽最大值作为最终生成图片的依据
      if (w !== this.width || h !== this.height) {
        var ratio;
        if (w > h) {
          ratio = this.width / w;
          h = this.height / ratio;
        } else if (w === h) {
          if (this.width > this.height) {
            ratio = this.width / w;
            h = this.height / ratio;
          } else {
            ratio = this.height / h;
            w = this.width / ratio;
          }
        } else {
          ratio = this.height / h;
          w = this.width / ratio;
        }
      }
      //以传入的长宽作为最终生成图片的尺寸
      if (w > h) {
        let offset = (w - h) / 2;
        canvas.width = canvas.height = w;
        ctx.drawImage(im, 0, offset, w, h);
      } else if (w < h) {
        let offset = (h - w) / 2;
        canvas.width = canvas.height = h;
        ctx.drawImage(im, offset, 0, w, h);
      } else {
        canvas.width = canvas.height = h;
        ctx.drawImage(im, 0, 0, w, h);
      }

      callback(canvas.toDataURL('image/jpeg'));
      //console.log('canvas.toDataURL---------->', canvas.toDataURL('image/jpeg'));
    };
    im.src = src;
  };

  handleCurrencyChange = value => {
    this.setState({ type: value });
    this.setState({ isChangeType: true });
  };
  handleCityChange = value => {
    this.setState({
      city: value,
      area: cityArea[value],
    });
  };
  handleUpload = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (this.state.type === 'media') {
          //console.log('Received values of form: ', values);
          const { fileList } = this.state;
          const params = values;
          fileList.forEach(file => {
            params[file.name] = file;
          });

          this.setState({
            uploading: true,
          });
          params.thumbnail = this.state.thumnaildata;
          //console.log('uploadfileList----------------->', fileList, params);
          this.props.dispatch({
            type: 'rule/uploadEditRule',
            payload: params,
            callback: () => {
              this.setState({
                fileList: [],
                uploading: false,
              });
              this.props.handleEditModalVisible(false);
              message.success('节目素材修改成功！');
              // this.props.dispatch({
              //   type: 'rule/fetch',
              //   payload: { page: 1, pageSize: 10 },
              // });
            },
          });

          // You can use any AJAX library you like
          // reqwest({
          //   url: 'http://47.106.151.60:10000/vehad/v1/uploadAdMat',
          //   method: 'post',
          //   processData: false,
          //   data: formData,
          //   type: 'json',
          //   success: () => {
          //     this.setState({
          //       fileList: [],
          //       uploading: false,
          //     });
          //     this.props.handleModalVisible(false);
          //     message.success('upload successfully.');
          //   },
          //   error: () => {
          //     this.setState({
          //       uploading: false,
          //     });
          //     this.props.handleModalVisible(false);
          //     message.error('upload failed.');
          //   },
          // });
        } else if (this.state.type === 'weather') {
          const { fileList } = this.state;
          const params = values;
          fileList.forEach(file => {
            params[file.name] = file;
          });
          this.props.dispatch({
            type: 'rule/uploadWeather',
            payload: params,
            callback: () => {
              this.props.handleEditModalVisible(false);
              message.success('素材编辑成功.');
              this.props.dispatch({
                type: 'rule/fetch',
              });
            },
          });
        } else if (this.state.type === 'traffic') {
          const { fileList } = this.state;
          const params = values;
          fileList.forEach(file => {
            params[file.name] = file;
          });
          this.props.dispatch({
            type: 'rule/uploadTraffic',
            payload: params,
            callback: () => {
              this.props.handleEditModalVisible(false);
              message.success('添加成功.');
              this.props.dispatch({
                type: 'rule/fetch',
              });
            },
          });
        }
      }
    });
  };

  render() {
    const uploadprops = {
      action: 'http://47.106.151.60:10000/vehad/v1/adupload',
      accept: 'image/*',
      onRemove: file => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(({ fileList }) => ({
          fileList: [file],
        }));
        const tempfiletype = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
        //console.log('tempfile--------->', tempfiletype);
        if (
          tempfiletype === 'jpg' ||
          tempfiletype === 'jpeg' ||
          tempfiletype === 'png' ||
          tempfiletype === 'GIF' ||
          tempfiletype === 'JPG' ||
          tempfiletype === 'PNG' ||
          tempfiletype === 'gif'
        ) {
          // 加载图片
          let obj = document.getElementById('video');
          obj.poster = this.getObjectURL(file);
          obj.setAttribute('poster', this.getObjectURL(file));
          obj.setAttribute('hidden', true);
          this.setImage(this.getObjectURL(file), 60, 40);
        }
        if (
          tempfiletype === 'MP4' ||
          tempfiletype === 'mp4' ||
          tempfiletype === 'ogg' ||
          tempfiletype === 'OGG' ||
          tempfiletype === 'WebM' ||
          tempfiletype === 'webm'
        ) {
          // 加载视频
          let obj = document.getElementById('video');
          obj.setAttribute('hidden', false);
          obj.hidden = false;
          obj.src = this.getObjectURL(file);
          setTimeout(() => {
            this.vload();
          }, 2000);
        }
        return false;
      },
      fileList: this.state.fileList,
    };
    const { editMmodalVisible, form, handleEditModalVisible, mat } = this.props;
    const { uploading, isChangeType, filetypenew, fileurl, fileList } = this.state;
    //console.log('fileList------------>', fileList);
    let { type } = this.state;
    const cityOptions = cityArray.map(city => <Option key={city}>{city}</Option>);
    const areaOptions = this.state.area.map(area => <Option key={area}>{area}</Option>);

    let filetype = '';
    const temp = mat.matType;
    //console.log('mat.matType------------>', mat.matType);
    if (temp === 0 || temp === 1 || temp === 2) {
      filetype = 'media';
    } else if (temp === 3) {
      filetype = 'weather';
    } else if (temp === 4) {
      filetype = 'traffic';
    }
    if (!isChangeType) {
      type = filetype;
    }

    return (
      <Modal
        title="编辑素材"
        visible={editMmodalVisible}
        onOk={this.handleUpload}
        onCancel={() => handleEditModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => handleEditModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={uploading}
            // disabled={this.state.fileList.length === 0}
            onClick={this.handleUpload}
          >
            {uploading ? '上传中...' : '修改'}
          </Button>,
        ]}
        destroyOnClose
      >
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="文件类型">
          {form.getFieldDecorator('filetype', {
            initialValue: type,
            rules: [{ required: true, message: '请输入文件名...' }],
          })(
            <Select onChange={this.handleCurrencyChange} style={{ width: 100 }}>
              <Select.Option value="media">图片视频</Select.Option>
              <Select.Option value="traffic">交通信息</Select.Option>
              <Select.Option value="weather">天气信息</Select.Option>
            </Select>
          )}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="文件名">
          {form.getFieldDecorator('fileName', {
            initialValue: mat.fileName,
            rules: [{ required: true, message: '请输入文件名...' }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="作者">
          {form.getFieldDecorator('author', {
            initialValue: mat.author,
            rules: [{ required: true, message: '请输入作者...' }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="单位名称">
          {form.getFieldDecorator('organName', {
            initialValue: mat.organName,
            rules: [{ required: true, message: '请输入单位名称...' }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
        {type === 'weather' ? (
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="城市">
            {form.getFieldDecorator('city', {
              rules: [{ required: true, message: '请输入单位名称...' }],
              initialValue: cityArray[0],
            })(
              <Select style={{ width: 90 }} onChange={this.handleCityChange}>
                {cityOptions}
              </Select>
            )}
          </FormItem>
        ) : null}
        {type === 'traffic' ? (
          <Fragment>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="城市">
              {form.getFieldDecorator('city', {
                rules: [{ required: true, message: '请输入单位名称...' }],
                initialValue: cityArray[0],
              })(
                <Select style={{ width: 180 }} onChange={this.handleCityChange}>
                  {cityOptions}
                </Select>
              )}
            </FormItem>
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="区域">
              {form.getFieldDecorator('distName', {
                rules: [{ required: true, message: '请输入单位名称...' }],
              })(
                <Select style={{ width: 180 }} onChange={this.onSecondCityChange}>
                  {areaOptions}
                </Select>
              )}
            </FormItem>
          </Fragment>
        ) : null}
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="文件链接">
          <a href={mat.matUrl}>{mat.fileName}</a>
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="缩略图">
          <video
            id="video"
            width="300"
            height="200"
            controls="controls"
            autoplay="autoplay"
            hidden="true"
          >
            <source id="mp4" src="" />{' '}
          </video>
          <Button onClick={() => this.vload()} hidden="true">
            截图
          </Button>
          <canvas className={styles.progress} id="thumnail_canvas" hidden="true" />
          <img id="thumnail" src={mat.thumbnail} width="60" height="40" />
          <img id="test" src="xx.jpg" width="60" height="40" hidden="true" />
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="选择文件">
          <Upload {...uploadprops}>
            <Button>
              <Icon type="upload" /> 选择文件
            </Button>
          </Upload>
          {/* <Button
            className="upload-demo-start"
            type="primary"
            onClick={this.handleUpload}
            disabled={this.state.fileList.length === 0}
            loading={this.state.uploading}
          >
            {uploading ? 'Uploading' : 'Start Upload'}
          </Button> */}
        </FormItem>
        <FormItem labelCol={{ span: 12 }} wrapperCol={{ span: 8 }} label="">
          {form.getFieldDecorator('matId', {
            initialValue: mat.matId,
          })(<Input readOnly type="hidden" />)}
        </FormItem>
      </Modal>
    );
  }
}
